#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tian'
__data__ = '2022/3/15 15:09'
# software: PyCharm

from django.shortcuts import HttpResponse, render
from django.http import JsonResponse

from apps.app01 import models

from apps.app01.forms.domain import DomainModelForm


def domain_list(request):
    """
    域名管理
    :param request:
    :return:
    """
    pid = request.GET.get("pid")  # pid是项目的pk
    if request.method == "GET" and not pid:
        it_obj = models.It.objects.all()
        return render(request, "all_item.html", {"it_dict": it_obj})
    domain_obj = models.Domain.objects.filter(project_id=pid)
    file_obj = models.It.objects.filter(pk=pid).first()
    form = DomainModelForm(request)
    if request.method == "GET":
        content = {
            "domain_obj": domain_obj,
            "file_obj": file_obj,
            "form": form

        }
        return render(request, "domain_table.html", content)

    # POST添加或编辑文件
    fid = request.POST.get("fid", "")
    edit_obj = None
    if fid.isdecimal():
        edit_obj = models.Domain.objects.filter(pk=fid).first()
    if edit_obj:
        form = DomainModelForm(request,data=request.POST, instance=edit_obj)
    else:
        form = DomainModelForm(request,data=request.POST)

    if form.is_valid():
        form.instance.project_id = pid
        form.save()
        return JsonResponse({"status": True})
    return JsonResponse({"status": False, "error": form.errors})


def domain_delete(request):
    """
    删除
    :param request:
    :return:
    """
    fid = request.GET.get("fid")
    del_obj = models.Domain.objects.filter(pk=fid).first()
    del_obj.delete()
    return JsonResponse({"status": True})
